<template>
  <div>
    <el-row style="height: 100%">
      <el-col :span="6">
        <div class="list-container">
          <div style="padding: 20px 40px;color: #6F7B7E;">
            共有 {{documents.content.length}} 条待标注数据
          </div>
          <div v-for="(item,index) in documents.content.slice(offset,offset+limit)" :key="index"
               :class="'list '+((index + offset === textID)?'active':'')" @click="loadText(index + offset)">
            <div class="list-icon">
              <i v-if="item.related" class="el-icon-success"></i>
            </div>
            <div class="list-text">
              {{item.context}}
            </div>
          </div>
        </div>

        <!--      下面的是占位用的不可删除-->
        <div style="min-height: 1px"></div>

      </el-col>
      <el-col :span="18" class="main-container">
        <!--        <div class="tag-container">-->
        <!--          <div class="tag" v-for="(item) in anno_data.connectionCategories" :key="item.id">-->
        <!--            {{item.text}}-->
        <!--            <i class="pointer icon ri-close-circle-line"-->
        <!--               @click="deleteConnectionCateConfirm(item.id)"-->
        <!--               @mouseover="mouseOver($event)" @mouseleave="mouseLeave($event)"></i>-->
        <!--          </div>-->
        <!--          <div class="pointer plus" @click="addConnectionCate">-->
        <!--            <i class="el-icon-plus"></i>-->
        <!--          </div>-->
        <!--        </div>-->
        <div class="info">
          <i class="el-icon-info"></i>
          左键点击标签增加关系，右键删除关系，双击推荐关系确认
        </div>
        <div id="example"></div>
        <div class="button-container">
          <span class="button level-left" @click="changePage(-1)"
                v-if="textID !== offset"
                v-shortkey="{next1: ['ctrl', 'p'], next2: ['arrowup'], next3: ['arrowleft']}"
                @shortkey="changePage(-1)"
          >&lt; 上一页</span>
          <span class="button level-right" @click="changePage(1)"
                v-shortkey="{next1: ['ctrl', 'n'], next2: ['arrowdown'], next3: ['arrowright']}"
                @shortkey="changePage(1)"
          >
            <span v-if="textID !== offset+limit-1">下一页 &gt;</span>
            <span v-if="textID === offset+limit-1 && textID !== documents.content.length-1">标记实体 &gt;</span>
            <span v-if="textID === offset+limit-1 && (textID === documents.content.length-1)">完成标记 &gt;</span>
          </span>
        </div>
      </el-col>

    </el-row>
    <el-dialog
        title="选择关系类型"
        :visible.sync="relationDialogVisible"
        :modal-append-to-body='false'
        width="30%">
      <!--      <span>选择关系类型</span>-->
      <div class="dialog-button-container">
        <div class="dialog-button pointer" @click="addConnection(item)"
             v-for="(item) in anno_data.connectionCategories.slice(0,connectionLength)" :key="item.id">
          {{item.text}}
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="relationDialogVisible = false">取 消</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import 'remixicon/fonts/remixicon.css'
import { Annotator} from 'poplar-annotation'
import axios from 'axios'
import {mapMutations} from "vuex";

let annotator = null;
let relationBaseUrl = "http://127.0.0.1:8000/"//后端地址
let fontUrl = "http://127.0.0.1:8000"
let projectid;
let max_id = 0;

export default {
  name: "Relation",
  data(){
    return{
      done:false,
      netdata:{"id":123123,"chunks":[{"id":0,"label":-1,"start_offset":0,"end_offset":24},{"id":1,"prob":0,"label":1,"start_offset":24,"end_offset":28},{"id":0,"label":-1,"start_offset":28,"end_offset":41},{"id":5,"prob":0,"label":4,"start_offset":41,"end_offset":43},{"id":0,"label":-1,"start_offset":43,"end_offset":73},{"id":3,"prob":0,"label":1,"start_offset":73,"end_offset":75},{"id":0,"label":-1,"start_offset":75,"end_offset":107},{"id":6,"prob":0,"label":4,"start_offset":107,"end_offset":112},{"id":0,"label":-1,"start_offset":112,"end_offset":124},{"id":7,"prob":0,"label":4,"start_offset":124,"end_offset":133},{"id":0,"label":-1,"start_offset":133,"end_offset":186}],"id2label":{"1":{"id":1,"text":"rew","shortcut":null,"background_color":"#209cee","text_color":"#ffffff","text_decoration":""},"4":{"id":4,"text":"注释","shortcut":"ctrl g","background_color":"#20ee49","text_color":"#ffffff","text_decoration":""},"-1":{"text_color":"","background_color":"","text_decoration":""}},"text":"The European Commission said on Thursday it disagreed with German advice to consumers to shun British lamb until scientists determine whether mad cow disease can be transmitted to sheep."},
      relationDialogVisible:false,
      documents:{},
      textID:null,
      anno_data:{
        content:"",
        labelCategories:[],
        labels:[],
        connectionCategories: [
          {
            "id": 0,
            "text": "修饰"
          },
          {
            "id": 1,
            "text": "限定"
          },
          {
            "id": 2,
            "text": "是...的动作"
          }
        ],
        connections:[]
      },
      labelSelect:{
        first:0,
        second:0,
      },
      annotator:{},
      items:{},
      labels:[],
      connectionLength:0,
      offset:0,
      limit:0,
      orilimit:0,//备份，用来返回
    }
  },
  methods:{
    ...mapMutations(['setAsideWidth']),
    changePage(delt){
      let textID = this.textID + delt
      if(textID < this.offset + this.limit && textID >= this.offset){
        this.loadText(textID)
      }
      if(textID === this.offset + this.limit){
        // console.log(textID === this.documents.content.length)
        // fontUrl
        if(textID !== this.documents.content.length)
          window.location.href=fontUrl+"/projects/"+projectid+"?offset="+(this.offset+ this.orilimit)
        else{
          window.location.href=fontUrl+"/projects/"+projectid+"/docs/"
        }
      }
    },
    mouseOver($event){
      $event.currentTarget.className = "pointer icon ri-close-circle-fill";
    },
    mouseLeave($event) {
      $event.currentTarget.className = "pointer icon ri-close-circle-line";
    },
    confirmConnection(id){
      axios({
        url:relationBaseUrl+"accRelationAnnotation/",
        method:"get",
        params:{
          id
        }
      }).then(res=>{
        res;
        this.download();
      })
    },
    deleteConnection(id){
      axios({
        url:relationBaseUrl+"delRelationAnnotation/",
        method:'get',
        params:{
          id,
        }
      }).then(res=>{
        res
        this.download();
      })
    },
    deleteConnectionCateCon(id){
      axios({
        url:relationBaseUrl+"delRelationLabel/",
        method:'get',
        params:{
          id,
        }
      }).then(res=>{
        res;
        this.download()
      })
    },
    deleteConnectionCateConfirm(id){
      this.$confirm('此操作将永久删除该关系名称, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        let usedCnt = 0;
        this.documents.content.forEach(content=>{
          content.connections.forEach(o=>{
            if(o.categoryId === id)usedCnt++;
          })
        })
        console.log('usdcnt',usedCnt);
        if(usedCnt > 0){
          this.$confirm('项目中还有<strong style="color: red">'+usedCnt+'</strong>处使用了该关系名称, 是否一同删除?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            dangerouslyUseHTMLString: true,
            type: 'warning'
          }).then(() => {
            this.deleteConnectionCateCon(id);
          })
        }else{
          this.deleteConnectionCateCon(id);
        }
      })
    },
    addConnectionCate(){
      console.log(annotator.store.connectionCategoryRepo)
      this.$prompt('', '新建关系', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputPlaceholder:"请输入关系名称",
      }).then(({ value }) => {
        this.anno_data = annotator.store.json
        axios({
          url:relationBaseUrl+'addRelationLabel/',
          method:'get',
          params:{
            project_id:projectid,
            text:value
          }
        }).then(res=>{

          let id = res.data;
          this.anno_data.connectionCategories.push({
            id,
            text:value
          })
          this.download();
        })
      })
    },
    addConnection(item){
      axios({
        url:relationBaseUrl+"addRelationAnnotation/",
        methods: 'get',
        params:{
          document_id:this.documents.content[this.textID].document_id,
          categoryId:item.id,
          fromId:this.labelSelect.first,
          toId:this.labelSelect.second
        }
      }).then(res=>{
        console.log(res)
        this.download();
        this.relationDialogVisible = false;
      })
    },
    download(){
      // 获取参数到id
      projectid = this.getParam("id")

      axios({
        method:'get',
        url:relationBaseUrl+"getData/",
        params: {
          project_id:projectid
        }
      }).then(res=>{
        console.log('dcy',res)

        this.documents = res.data;

        //设置关系属性
        this.anno_data.connectionCategories = this.documents.connectionCategories
        //增加推荐属性
        this.connectionLength = this.anno_data.connectionCategories.length

        max_id = 0;
        let cate = this.anno_data.connectionCategories;
        cate.forEach(c=>{
          max_id = Math.max(c.id,max_id)
        })
        for (let i = 0; i < this.connectionLength; i++) {
          cate.push({
            id:cate[i].id+max_id,
            text: cate[i].text+"（推荐）",
          });
        }

        this.loadText(this.textID);
      })
    },
    loadText(textID){
      if(textID === null){
        textID = this.offset;
      }
      this.textID = textID
      // 截取

      this.offset = parseInt(this.getParam("offset"))
      if(!this.offset)this.offset = 0;
      this.limit = parseInt(this.getParam("limit"))
      this.orilimit = this.limit
      if(!this.limit)this.limit = this.documents.content.length;
      this.limit = Math.min(this.limit,this.documents.content.length - this.offset)

      //设置文本
      this.anno_data.content = this.documents.content[textID].context

      //设置标签属性
      this.anno_data.labelCategories = this.documents.label_list

      //设置标签
      this.anno_data.labels = this.documents.content[textID].labels



      //设置关系
      this.anno_data.connections = this.documents.content[textID].connections
      //处理字符数字类型问题
      this.anno_data.connections.forEach(e=>{
        e.fromId = parseInt(e.fromId)
        e.toId = parseInt(e.toId)
        if(e.isRecommend){
          e.categoryId += max_id
        }
      })


      this.createAnnotator()
    },
    createAnnotator(){
      if(annotator)annotator.remove();

      // 奇怪的bug，刚开始无法获取example
      if(document.getElementById("example") === null){
        this.$nextTick(this.createAnnotator)
        return;
      }

      console.log('dcy',this.anno_data)
      annotator = new Annotator(this.anno_data,document.getElementById("example"),{
        topContextMargin:15,
        labelPadding:5,
      })
      // 点击两个标签添加关系
      annotator.on('twoLabelsClicked', (first, second) => {
        // 输出用户选取的两个label的ID
        this.labelSelect = {first,second}
        this.relationDialogVisible = true;
      });

      // 右键关系删除
      annotator.on('connectionRightClicked', (id, event) => {
        this.deleteConnection(id)
        event;
      });

      // 双击关系确认
      annotator.on('connectionDoubleClicked', (id, event) => {
        this.confirmConnection(id)
        console.log(id, event);
      });
    },
    getParam(name){
      try{
        let reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)","i");
        return window.location.search.substr(1).match(reg)[2];
      }catch (e) {
        return null;
      }
    }
  },
  mounted(){
    this.textID = parseInt(this.getParam("offset"))
    if(!this.textID)this.textID = 0;
    this.setAsideWidth(0);
    this.download()
  },
}
</script>

<style scoped>
.list-container{
  position: fixed;
  min-height: calc(100% - 100px);
  max-height: calc(100% - 100px);
  overflow-y: scroll;
  width: 25%;
  background-color: #2a2e2f;
}
.list-container::-webkit-scrollbar {
  display: none;
}
.active{
  background-color: #5a5e5f;
}
.list{
  cursor: pointer;
  padding: 15px 10px 15px 15px;
  font-size: 15px;
  color: #f3f3f3;
  font-weight: 500;
  max-height: 80px;
  margin-top: 1px;
}
.list-icon{
  float: left;
  font-weight: bolder;
  font-size: large;
  margin-top: 2px;
  width: 30px;
}
.list-text{
  overflow:hidden;
  text-overflow:ellipsis;
  display:-webkit-box;
  -webkit-box-orient:vertical;
  -webkit-line-clamp:3;
}
.list:hover{
  background-color: #5a5e5f;
}
.main-container{

}
/deep/ #example > svg {
  width: 100%;
  font-size: 20px;
}
/deep/ #example{
  width: 90%;
  margin:0px auto 0 auto;
}

/deep/ .v-modal{
  background-color: #9d9d9d;
}
.tag > .icon{
  position: absolute;
  top:-5px;
  font-size: 18px;
  font-weight: 100;
  right: -7px;
  background-color: white;
}
.tag-container {
  padding-top: 50px;
  width: 85%;
  height: 100px;
  margin:0px auto -10px auto;
}
.plus{
  margin: 0 8px 8px 8px;
  width: 38px;
  height: 36.4px;
  text-align: center;
  /*padding:8px 10px 8px 10px;*/
  border: 1px #343c96 solid;
  color: #343c96;
  border-radius: 10px;
  float: left;
}
.plus i{
  margin-top: 10px;
}
.info{
  color: #b5b5b5;
  width: 90%;
  margin:30px auto 20px auto;
  padding-left: 60px;
}

.dialog-button-container{
  padding:0 10px 10px 10px;
  margin-bottom: 20px;
}
.pointer{
  cursor: pointer;
}
.tag{
  position: relative;
}

.level-left {
  float: left;
}
.level-right {
  float: right;
}

.level-left, .level-right {
  flex-basis: auto;
  flex-grow: 0;
  flex-shrink: 0;
}
.button-container{
  width: 83%;
  margin:0 auto 0 auto;
}

.button {
  position: relative;
  background-color: #fff;
  border: 1px #dbdbdb solid ;
  border-radius: 6px;
  color: #363636;
  cursor: pointer;
  justify-content: center;
  padding-bottom: calc(.375em - 1px);
  padding-left: .75em;
  padding-right: .75em;
  padding-top: calc(.375em - 1px);
  text-align: center;
  white-space: nowrap;
  font-size: 17px;
  font-weight: 600;
}

.button:hover{
  border: 1px #a9a9a9 solid;
}

.dialog-button, .tag{
  margin: 0 8px 8px 8px;
  padding:8px 10px 8px 10px;
  border: 1px #343c96 solid;
  color: #343c96;
  border-radius: 10px;
  float: left;
}
.dialog-button:hover{
  background-color: #343c96;
  color: white;
}


</style>